package com.sa.app.utilities;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.sa.app.R;
import com.sa.app.activities.ItemActivity;
import com.sa.app.activities.MainActivity;

public class AsynchronousDownloaderImg extends
AsyncTask<String, Float, Integer> {

	private DataBaseManager dbm;
	private ProgressDialog progressDialog;
	private File img;
	private String NFCID;
	private ItemXMLParser parser;
	private Context cont;
	private MainActivity ma;
	private final Integer TIME_TO_COMPLETED = 10;
	private Boolean networkError;
	private Boolean locationError = false;

	public AsynchronousDownloaderImg(MainActivity ma, Context c,
			DataBaseManager dbm, ItemXMLParser parser, String NFCID,
			Boolean networkError) {
		this.cont = c;
		this.ma = ma;
		this.img = c.getFilesDir();
		this.NFCID = NFCID;
		progressDialog = new ProgressDialog(c);
		progressDialog.setMessage(ma.getString(R.string.preparing));
		this.parser = parser;
		this.dbm = dbm;
		this.networkError = networkError;
	}

	protected void onPreExecute() {

		progressDialog.show();
	}

	protected Integer doInBackground(String... urls) {

		Integer res = 1;

		URL miUrl = null;
		try {
			miUrl = new URL(urls[0]);

			// Se crea la conexión http
			HttpURLConnection conn = (HttpURLConnection) miUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();

			File f = new File(img.getAbsolutePath() + "/" + NFCID + ".png");

			// Se lee el stream de datos de la imagen
			InputStream is = conn.getInputStream();

			// Se reconstruye la imagen a partir del stream de datos
			OutputStream out = new FileOutputStream(f);
			byte buf[] = new byte[1024];
			int len;
			while ((len = is.read(buf)) > 0)
				out.write(buf, 0, len);
			out.close();
			is.close();

		} catch (IOException e) {
			Log.i("Error en downloadBitmap",
					"¿Hay conexión a internet?¿La url es correcta, "
							+ urls[0] + "?");
			networkError = true;
			res = -1;
			e.printStackTrace();
		}

		// Busqueda de ubicacion
		MyApplication mApp = (MyApplication) ma.getApplicationContext();
		Location loc = mApp.getLocation();

		int i = 0;
		while (i < TIME_TO_COMPLETED
				&& (loc == null | loc.getAccuracy() >= mApp.getMinGpsAccuracy())) {

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;
			loc = mApp.getLocation();

		}

		if (loc == null | loc.getAccuracy() >= mApp.getMinGpsAccuracy()) {
			locationError = true;
		}

		return res;
	}

	protected void onProgressUpdate(Float... valores) {

	}

	protected void onPostExecute(Integer bytes) {

		if (!networkError && !locationError) {

			MyApplication mApp = (MyApplication) ma.getApplicationContext();
			Location loc = mApp.getLocation();

			// Metodo que decide si hay region existente o bien se crea la
			// nueva.

			Integer latitude = Integer.valueOf((int) (loc.getLatitude() * 1E6));
			Integer longitude = Integer
					.valueOf((int) (loc.getLongitude() * 1E6));
			Integer accuracy = Integer.valueOf((int) (loc.getAccuracy()));

			List<String> region = dbm.getRegionFor(latitude, longitude,
					accuracy);
			List<String> use = new ArrayList<String>();
			use.add(NFCID);
			use.add(region.get(1));
			use.add(region.get(2));
			use.add(String.valueOf(MyApplication.TAGGED));
			// Encadenar con el insertAll.
			dbm.insertAll(parser.getItem(), parser.getDatasheet(),
					parser.getVirtualServices(), parser.getRealServices(),
					parser.getVirtualParams(), parser.getRealParams(),
					parser.getVirtualSecurity(), parser.getRealSecurity(),
					region, use);
			progressDialog.dismiss();
			Intent intent = new Intent(cont, ItemActivity.class);

			String[] array = { parser.getItem().get(0) };

			intent.putExtra("item", array);

			intent.setAction("ItemsFragment");

			ma.startActivity(intent);
		} else {

			String msg = ma.getString(R.string.error) + "\n";
			if (networkError) {
				msg += ma.getString(R.string.network_error) + "\n";
			}
			if (locationError) {
				msg += ma.getString(R.string.location_error) + "\n";
			}
			msg += ma.getString(R.string.sorry);

			Toast.makeText(cont, msg, Toast.LENGTH_SHORT).show();
			progressDialog.dismiss();

		}
	}

}